package rsj.job;

import com.rlyy.aibase.utils.base.TableNode;
import common.util.DateTimeFormatterUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import rsj.service.IExecuteInterface;
import rsj.utils.RedisUtils;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author yuanqinglong
 * @since 2021/4/1 9:37
 */
@Component
public class UpdateTestResult {

    Logger logger = LoggerFactory.getLogger(UpdateTestResult.class);
    /**
     * redis状态为2、98、99时删除redis
     */
    private static final Set<String> DELETE_RESULT = new HashSet<>();

    static {
        DELETE_RESULT.add("2");
        DELETE_RESULT.add("98");
        DELETE_RESULT.add("99");
    }

    public void queryTodayTestData(TableNode tableNode) {
        String time = DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now());
        logger.info("统计测试数据解析结果定时任务：执行时间:{}", time);
        if (tableNode.length() > 0) {
            this.queryParseResult(tableNode);
        }
    }

    /**
     * 查询测试数据解析结果
     *
     * @param tableNode 测试数据
     */
    private void queryParseResult(TableNode tableNode) {
        List<Map<String, Object>> maps = tableNode.toList();
        for (Map<String, Object> map : maps) {
            String logId = (String) map.get("Log_Id");
            String taskName = "rsjmq:" + logId;
            String result = RedisUtils.getString(taskName);
            logger.info("taskName：{},解析状态:{}", taskName, result);
            boolean delete = StringUtils.isNotBlank(result) && DELETE_RESULT.contains(result);
            logger.info("是否满足删除taskName条件：{}", delete);
            if (delete) {
                map.put("Log_Result", result);
                this.updateTestResult(result, logId);
                RedisUtils.del(taskName);
            }
        }

    }

    /**
     * 更新测试结果
     *
     * @param result 结果
     * @param logId  id
     */
    private void updateTestResult(String result, String logId) {
        String sql = " UPDATE sys.sys_test_log SET log_result = '" + result + "' WHERE log_id = '" + logId + "'";
        IExecuteInterface.doExecuteUpdate(sql, e -> logger.error("更新测试数据解析结果异常,日志ID:{},{}", logId, e));
    }

}
